package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Fibonacci Series
 * 
 * Description:
 * 
 * The Fibonacci series is defined as: F(0) = 0; F(1) = 1; F(n) = F(n-1) + F(n-2) when n>1;. Given a
 * positive integer 'n', print out the F(n).
 * 
 * Input sample:
 * 
 * The first argument will be a text file containing a positive integer, one per line. e.g.
 * 
 * 5
 * 12
 * 
 * Output sample:
 * 
 * Print to stdout, the fibonacci number, F(n).
 * e.g.
 * 
 * 5
 * 144
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 * 
 */
public class fibonacci {
	/**
	 * Calculates the {@code n}th element of the Fibonacci sequence.
	 * 
	 * @param n The element of the Fibonacci sequence to retrieve.
	 * @return the Fibonacci number {@code F(n)}.
	 */
	private static int fib(final int n) {
		if (n == 1 || n == 0) {
			return 1;
		} else {
			return fib(n - 1) + fib(n - 2);
		}
	}

	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;

		while ((line = reader.readLine()) != null) {
			try {
				// Get the value of "n".
				final int n = Integer.parseInt(line);

				if (n < 1) {
					throw new RuntimeException("Only positive integers are supported.");
				}

				System.out.println(fib(n - 1));
			} catch (final NumberFormatException e) {
				throw new RuntimeException("Input file contained non-numeric arguments.");
			}
		}
	}
}
